package com.castile.oa;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.SecureClassLoader;

/**
 * @description: 从.myclass 文件中加载对象
 * @author: Castile
 * @create: 2024-04-10 23:36
 * @Version 1.0
 **/
public class SalaryClassLoader extends SecureClassLoader {

    private String classPath;

    public SalaryClassLoader(String classPath) {
        this.classPath = classPath;
    }

    /**
     * 从.myclass 文件中加载对象
     *
     * @param name The <a href="#name">binary name</a> of the class
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        // myclass的路径
        String filePath = this.classPath + name.replace(".", "\\").concat(".myclass");
        File file = new File(filePath);
        FileInputStream fis = null;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        byte[] b = new byte[100];
        int code;
        try {
            fis = new FileInputStream(file);

            while ((code = fis.read()) != -1) {
                byteArrayOutputStream.write(code);
            }
            b = byteArrayOutputStream.toByteArray();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {

                try {
                    fis.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        System.out.println("myclass 字节数组大小为： "+ b.length);
        return this.defineClass(name, b, 0, b.length);
    }
}
